<?php
  
 
  class RegisterController extends BaseController {
      
        public $patterns = array(   
        							'mobile'   => '(\\+44)?\r\n(\\s+)?\r\n(\\(?)\r\n(?<area_code>(\\d{1,5}|\\d{4}\\s+"+
      "?\\d{1,2}))(\\)?)\r\n(\\s+|-)?\r\n(?<tel_no>\r\n(\\d{1,4}\r\n(\\s+|-"+
      ")?\\d{1,4}\r\n|(\\d{6})\r\n))',
        							'postcode' => '^(([gG][iI][rR] {0,}0[aA]{2})|((([a-pr-uwyzA-PR-UWYZ][a-hk-yA-HK-Y]?[0-9][0-9]?)|(([a-pr-uwyzA-PR-UWYZ][0-9][a-hjkstuwA-HJKSTUW])|([a-pr-uwyzA-PR-UWYZ][a-hk-yA-HK-Y][0-9][abehmnprv-yABEHMNPRV-Y]))) {0,}[0-9][abd-hjlnp-uw-zABD-HJLNP-UW-Z]{2}))$');
        							
        public $rules = array(
        						'firstname'  => 'required|max:255',
        						'lastname'   => 'required|max:255',
        						'password'   => 'required|max:255',
        						'email'      => 'required|email|unique:user_credentials,email',
        						'mobile'     => 'required|numeric|max:10',
        						'postcode'   => 'required|',
        						'trade_name' => 'required|unique:user_credentials,trade_name|alpha_num',
        						'trades'     => 'required');
        						
        
        						
        public function __construct(){ }
        
        public function index(){
            return View::make('register.create')->with('messages', false);
        }  
        
        public function store(){
            
            $user = new User();
            
            $user->firstname = Input::get('firstname');
            $user->lastname = Input::get('lastname');
            $user->password = Hash::make(Input::get('password'));
            $user->email = Input::get('email');
            $user->mobile = Input::get('mobile');
            $user->postcode = Input::get('postcode');
            $user->trade_name = Input::get('trade_name');
            $user->trades = Input::get('trades');
            
            $tradeName = Input::get('trade_name');
            $password  = Input::get('password');
            
            $validator = Validator::make(Input::except('hidden-trades'), $this->rules);
            
            if($validator->fails()){
				return View::make('register.create')->with('messages', $validator->messages());
			} else {
            	
            	if($user->save()){
            	
            		if(Auth::attempt(['trade_name' => $tradeName, 'password' => $password])){
            			Session::put('uname', $tradeName);
						return Redirect::to('profile');
					} else {
						return 'auth failed';
            		}	
				} else {
					return 'There was some fracking error';
            	}
			}
        }
  }